import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import LoginView from "@/views/LoginView.vue";
import RegisterView from "@/views/RegisterView.vue";
import IndexView from "@/views/IndexView.vue";
import UserCenter from "@/views/UserCenter.vue";
import UserInfoView from "@/views/user_center/UserInfoView.vue";

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'home',
        component: HomeView,
        children: [
            {
                path: 'index',
                name: 'index',
                component: IndexView
            }
        ]
    },
    {
        path: '/login',
        name: 'login',
        component: LoginView
    },
    {
        path: '/register',
        name: 'register',
        component: RegisterView
    },
    {
        path: '/userCenter',
        name: 'UserCenter',
        component: UserCenter,
        children: [
            {
                path: 'info',
                name: 'UserInfo',
                component: UserInfoView,
            }
        ]
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})
import {api} from '@/assets/static/js/settings'
import store from "@/store";

router.beforeEach((to, from, next) => {
    let hasRoute = store.state.hasRoutes  //在状态管理器里存的路由信息
    let token = Vue.prototype.$cookies.get("token")
    if (to.path === '/login' || to.path === '/register') {//登陆或注册页面，直接走
        store.commit('setRedirecting', false); // 重置标志
        next()
        return;
    } else if (!token) {  //token不存在，跳转到登陆页面
        next({path: '/login'})
        return;
    } else if (token && !hasRoute) {//token存在并且hasRoute没有信息，进行网络请求，获取导航
        Vue.prototype.$axios.get(api.menu, {
            headers: {
                token: Vue.prototype.$cookies.get("token")
            }
        }).then(res => {
            if (res) {
                // 拿到menuList
                store.commit("setMenuList", res.nav)
                // 拿到用户权限
                store.commit("setPermList", res.authority)
                // 动态绑定路由
                let newRoutes = router.options.routes
                // 遍历返回的nav
                res.nav.forEach(menu => {
                    if (menu.menus) {
                        menu.menus.forEach(e => {
                            // 转成路由
                            let route = menuToRoute(e)
                            // 添加到路由管理中
                            if (route) {
                                newRoutes[0].children.push(route)
                            }
                        })
                    }
                })
                // vue-router3.x有addroutes方法，4.x就废弃了
                router.addRoutes(newRoutes)
                hasRoute = true
                store.commit("changeRouteStatus", hasRoute)
            }
        })
    }
    next();

})
const menuToRoute = (menu) => {
    if (!menu.component) {
        return null
    }
    let route = {
        name: menu.name,
        path: menu.path,
        meta: {
            icon: menu.icon,
            title: menu.title
        }
    }
    // route.component = () => import('@/views/' + menu.component + '.vue')
    route.component = () => {
        try {
            return import('@/views/' + menu.component + '.vue');
        } catch (e) {
            console.error('Error loading component:', e);
            return null;
        }
    }
    return route
}

export default router
